﻿namespace WLFramework.Validation
{
    using System;

    [AttributeUsage(AttributeTargets.Property)]
    public class DateEndAttribute : ValidationAttribute
    {
        public string PropertyName { get; set; }
        public string TargetDisplayName { get; private set; }

        public DateEndAttribute(string property) :
            this(property,"\'{0}\' 的日期不能小于 \'{1}\' 的日期！")
        { 
        }

        public DateEndAttribute(string property,string displayErrors)
            : this(property,displayErrors, "请输入{0}")
        {
        }

        public DateEndAttribute(string property, string displayErrors, string displayDefault)
        {
            this.PropertyName = property;
            this.ErrorMessage = displayErrors;
            this.DefaultMessage = displayDefault;
        }

        public override ValidatePriority Priority
        {
            get
            {
                return ValidatePriority.High;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(this.ErrorMessage, name, this.TargetDisplayName);
        }

        public override ValidateResult IsValid(object input, ValidateContext context)
        {
            this.TargetDisplayName = context.Metadata.GetMemberDisplayName(this.PropertyName);

            if (DateTime.Compare(
                    Convert.ToDateTime(input),
                    Convert.ToDateTime(context.Metadata.GetMemberValue(this.PropertyName))) == -1)
            {
                return new ValidateResult(this.FormatErrorMessage(context.DisplayName));
            }

            return ValidateResult.Success;
        }
    }
}

